using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;

using A4G.Core;

namespace A4G.Core
{
	public class FastaFile
	{
		private const string _fastaRegex = @"\s{0,}>(?<name>[A-Za-z0-9_,. \(\)\-]{1,})\s{1,5}(?<sequence>([ACGTacgt\s]{1,}))";

		public FastaFile(string fileName)
		{
			_filename = fileName;
		}

		private readonly string _filename;
		public string Filename
		{
			get
			{
				return _filename;
			}
		}

		public void Load()
		{
			StreamReader reader = new StreamReader(Filename);
			try
			{
				string fastaInput = reader.ReadToEnd();

				Regex fastaRegex = new Regex(_fastaRegex, RegexOptions.Multiline);
				MatchCollection matches = fastaRegex.Matches(fastaInput);

				foreach (Match match in matches)
				{
					string sequence = match.Result("${sequence}");
					sequence = sequence.Replace("\n", "");
					sequence = sequence.Replace("\r", "");

					Sequence newSequence = new Sequence(
						match.Result("${name}"),
						sequence);
					Sequences.Add(newSequence);
				}
			}
			finally
			{
				reader.Close();
			}
		}

		public void Save()
		{
			StreamWriter writer = new StreamWriter(Filename);
			try
			{

				foreach (Sequence sequence in Sequences)
				{
					writer.WriteLine(">" + sequence.Name);

					string sqnc = sequence.SequenceString;
					for (int i = 0; i < sqnc.Length; i += 100)
					{
						int length = Math.Min(100, (sqnc.Length) - i);
						writer.WriteLine(sqnc.Substring(i, length));
					}
				}
			}
			finally
			{
				writer.Close();
			}
		}

		private ArrayList _sequences = new ArrayList();
		public ArrayList Sequences
		{
			get
			{
				return _sequences;
			}
			set
			{
				_sequences = value;
			}
		}
	}
}
